package com.hao.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * TODO
 *
 * @author 97472
 * @version 1.0
 * @date 2021/11/25 16:17
 */
public class NettyClient {
    public static void main(String[] args) {
        try {
            // 创建线程组
            EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

            // 创建netty客户端启动对象
            Bootstrap bootstrap = new Bootstrap();

            // 对启动对象进行配置
            bootstrap.group(eventLoopGroup)// 配置线程组
                    .channel(NioSocketChannel.class) // 配置客户端使用的通道
                    .handler(new ChannelInitializer<SocketChannel>() {// 配置客户端使用的handler处理器
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });

            // 连接服务端
            ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("127.0.0.1", 6789)).sync();
            channelFuture.channel().writeAndFlush("000");
            // 对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
